<template>
  <div>
    <el-upload
      action="/api/upload"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :limit="limitCount"
      :file-list="defaultImgList"
      :class="{ hide: showUpload }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop, Emit } from "vue-property-decorator";

@Component({
  name: "upload",
})
export default class extends Vue {
  @Prop() private defaultImg: any;
  @Prop() private theme:string

  private fileList = [];
  private limitCount: number = 2;
  private dialogImageUrl: string = "";
  private dialogVisible: boolean = false;
  private showUpload: boolean = false; //指定上传数后 关闭上传按钮
  private defaultImgList = [];

  private mounted() {
    this.defaultImgList = this.defaultImg?JSON.parse(this.defaultImg):[];
    
    this.fileList = this.defaultImg?JSON.parse(this.defaultImg):[];
  }

  // 上传前
  private beforeAvatarUpload(file) {
    const isJPG = file.type === "image/jpeg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
      this.$message.error("上传头像图片只能是 JPG 格式!");
    }
    if (!isLt2M) {
      this.$message.error("上传头像图片大小不能超过 2MB!");
    }
    return isJPG && isLt2M;
  }

  // 上传成功
  private handleAvatarSuccess(res, file) {
      
    let one_url = {
      url: res.url,
    };
    this.fileList.push(one_url);
    this.showUpload = this.fileList.length >= this.limitCount;
    this.uploadHandle();
  }

  //预览
  private handlePictureCardPreview(file) {
    this.dialogImageUrl = file.url;
    this.dialogVisible = true;
  }
  //删除
  private handleRemove(file, fileList) {
    
    let delete_url = file.url;
    const index = this.fileList.findIndex((ele: any) => {
      return ele.url == delete_url;
    });

    this.fileList.splice(index, 1);
    this.showUpload = fileList.length >= this.limitCount;
   console.log("showUpload:"+this.showUpload)
    this.uploadHandle();
  }

  @Emit("uploadHandle")
  private uploadHandle() {
    var obj = {
      theme: this.theme,
      fileList:this.fileList
    }
    return obj;
  }
}
</script>
<style >
.hide .el-upload--picture-card {
  display: none;
}
</style>